<template>
  <div id="app">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header style="background-color: #3a8ee6; color: white; text-align: center; line-height: 60px;">
        <h1 style="margin: 0;">{{ title }}</h1>
      </el-header>
      
      <el-container>
        <!-- 左侧菜单栏 -->
        <el-aside :width="isMenuCollapse ? '60px' : '200px'" style="background-color: #304156; padding: 0; transition: width 0.3s;">
          <el-menu 
            background-color="#304156" 
            text-color="#fff" 
            active-text-color="#409EFF" 
            unique-opened
            :collapse="isMenuCollapse" 
            :collapse-transition="false"
          >
            <!-- 动态渲染菜单 -->
            <template v-for="menu in menus">
              <el-menu-item
                v-if="!menu.children || menu.children.length === 0"
                :key="menu.id"
                :index="menu.id.toString()"
                @click="handleMenuClick(menu.path, menu.menuName)">
                <i v-if="menu.icon" :class="menu.icon"></i>
                <span slot="title">{{ menu.menuName }}</span>
              </el-menu-item>
              
              <el-submenu
                v-else
                :key="menu.id"
                :index="menu.id.toString()">
                <template slot="title">
                  <i v-if="menu.icon" :class="menu.icon"></i>
                  <span>{{ menu.menuName }}</span>
                </template>
                <el-menu-item
                  v-for="child in menu.children"
                  :key="child.id"
                  :index="child.id.toString()"
                  @click="handleMenuClick(child.path, child.menuName)">
                  <i v-if="child.icon" :class="child.icon"></i>
                  <span slot="title">{{ child.menuName }}</span>
                </el-menu-item>
              </el-submenu>
            </template>
          </el-menu>
        </el-aside>
        
        <!-- 主内容区域 -->
        <el-main :style="{ padding: '20px', transition: 'margin-left 0.3s' }">
          <!-- 菜单伸缩按钮（内容左上角） -->
          <div class="content-menu-toggle-btn" @click="toggleMenu">
            <i :class="isMenuCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'" style="color: white;"></i>
          </div>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      menus: []
    };
  },
  mounted() {
    this.loadMenus();
  },
  data() {
    return {
      menus: [],
      title: 'DST数据同步工具', // 默认标题
      isMenuCollapse: false // 菜单展开/收起状态
    };
  },
  mounted() {
    this.loadMenus();
    this.loadSystemConfig();
  },
  methods: {
    // 加载系统配置
    loadSystemConfig() {
      // 检查API是否可用
      if (!this.$api || !this.$api.systemConfigApi) {
        console.error('API对象或systemConfigApi不存在');
        return;
      }
      
      this.$api.systemConfigApi.getAll()
        .then(res => {
          const configData = res && res.data || [];
          
          // 查找系统标题配置
          const titleConfig = configData.find(config => 
            config.configKey === 'SYSTEM_TITLE' && config.isEnabled
          );
          
          if (titleConfig && titleConfig.configValue) {
            this.title = titleConfig.configValue;
            console.log('系统标题已更新为:', this.title);
          } else {
            console.warn('未找到有效的系统标题配置，使用默认标题');
          }
        })
        .catch(error => {
          console.error('获取系统配置失败:', error);
          // 保留默认标题
        });
    },
    handleMenuClick(path, menuName) {
      console.log(`点击菜单: ${menuName}, 路径: ${path}`);
      this.$router.push(path);
    },
    // 切换菜单展开/收起状态
    toggleMenu() {
      this.isMenuCollapse = !this.isMenuCollapse;
    },
    loadMenus() {
      this.$api.menuApi.getAll()
        .then(res => {
          const menuData = res && res.data || [];
          // 筛选出启用且可见的菜单
          const visibleMenus = menuData.filter(menu => menu.isEnabled && menu.isVisible);
          
          if (visibleMenus.length > 0) {
            // 构建菜单树结构
            this.menus = this.buildMenuTree(visibleMenus);
          } else {
            // 如果没有从API获取到菜单，显示默认菜单
            console.warn('从API获取的菜单列表为空，显示默认菜单');
            this.showDefaultMenus();
          }
        })
        .catch(error => {
          console.error('获取菜单列表失败:', error);
          // 如果API调用失败，显示默认菜单
          this.showDefaultMenus();
        });
    },
    
    // 构建菜单树结构
    buildMenuTree(menus) {
      const menuMap = {};
      const rootMenus = [];
      
      // 先将所有菜单放入map中
      menus.forEach(menu => {
        // 清理图标格式，确保图标正确显示
        const cleanIcon = menu.icon ? menu.icon.trim() : '';
        menuMap[menu.id] = { 
          ...menu, 
          icon: cleanIcon, 
          children: [] 
        };
      });
      
      // 构建树状结构
      menus.forEach(menu => {
        if (menu.parentId && menu.parentId !== 0) {
          // 有父菜单
          if (menuMap[menu.parentId]) {
            menuMap[menu.parentId].children.push(menuMap[menu.id]);
          }
        } else {
          // 顶级菜单
          rootMenus.push(menuMap[menu.id]);
        }
      });
      
      // 按排序号排序
      rootMenus.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
      rootMenus.forEach(menu => {
        if (menu.children && menu.children.length > 0) {
          menu.children.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
        }
      });
      
      return rootMenus;
    },
    
    // 当API调用失败时显示默认菜单
    showDefaultMenus() {
      this.menus = [
        {
          id: 1,
          menuName: '首页',
          path: '/',
          icon: 'el-icon-s-home',
          children: []
        },
        {
          id: 2,
          menuName: '系统管理',
          path: '/system',
          icon: 'el-icon-setting',
          children: [
            {
              id: 12,
              menuName: '系统配置管理',
              path: '/system-config',
              icon: 'el-icon-setting',
              children: []
            },
            {
              id: 13,
              menuName: '菜单管理',
              path: '/menu',
              icon: 'el-icon-menu',
              children: []
            }
          ]
        },
        {
          id: 3,
          menuName: '数据同步管理',
          path: '/service',
          icon: 'el-icon-s-promotion',
          children: [
            {
              id: 14,
              menuName: '服务信息管理',
              path: '/service-management',
              icon: 'el-icon-s-marketing',
              children: []
            },
            {
              id: 15,
              menuName: '服务类型管理',
              path: '/service-type-management',
              icon: 'el-icon-s-operation',
              children: []
            }
          ]
        },
        {
          id: 4,
          menuName: '数据库管理',
          path: '/database',
          icon: 'el-icon-s-data',
          children: [
            {
              id: 16,
              menuName: '数据库配置',
              path: '/database-config',
              icon: 'el-icon-s-tools',
              children: []
            },
            {
              id: 17,
              menuName: '同步策略',
              path: '/sync-strategy',
              icon: 'el-icon-s-operation',
              children: []
            },
            {
              id: 18,
              menuName: '数据库表结构',
              path: '/schema',
              icon: 'el-icon-s-grid',
              children: []
            },
            {
              id: 19,
              menuName: '区域管理',
              path: '/area-management',
              icon: 'el-icon-s-grid',
              children: []
            },
            {
              id: 20,
              menuName: '设备管理',
              path: '/device-management',
              icon: 'el-icon-monitor',
              children: []
            }
          ]
        },
        {
          id: 5,
          menuName: '数据迁移',
          path: '/data-migration',
          icon: 'el-icon-s-exchange',
          children: []
        },
        {
          id: 6,
          menuName: '帮助文档',
          path: '/help',
          icon: 'el-icon-s-help',
          children: []
        }
      ];
    }
  }
};
</script>

<style>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
}

#app {
  height: 100%;
}

/* Element UI 样式覆盖 */
.el-header {
  height: 60px !important;
  padding: 0 !important;
}

.el-aside {
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.el-main {
  height: calc(100vh - 60px);
  overflow-y: auto;
  padding: 20px;
}

/* 菜单样式 */
.el-menu {
  border-right: none;
}

/* 内容区域菜单伸缩按钮样式 */
.content-menu-toggle-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 40px;
  height: 28px;
  border-radius: 4px;
  background-color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0,0,0,0.25);
  transition: all 0.3s ease;
}

/* 按钮图标样式 */
.content-menu-toggle-btn i {
  font-size: 18px;
  color: white;
  transition: transform 0.3s ease;
}

/* 按钮悬停效果 */
.content-menu-toggle-btn:hover {
  background-color: #66b1ff;
  box-shadow: 0 4px 12px rgba(0,0,0,0.35);
  transform: translateY(-1px);
}

.content-menu-toggle-btn:hover i {
  transform: scale(1.1);
}

/* 按钮点击效果 */
.content-menu-toggle-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}
</style>